var cluster = require('cluster')
var numCPUs = require('os').cpus().length;

//master process
if (cluster.isMaster) 
{
    // 클러스터 워커 프로세스 포크
    for (var i = 0; i < numCPUs; i++) 
	{
        cluster.fork();
    }
 
    cluster.on('exit', function(worker, code, signal) 
	{
        console.error('worker ' + worker.process.pid + ' died');
		// 줙으면 하나 더 띄운다.
        cluster.fork();
    });

} 
//worker process
else 
{
	var express = require('express')
	  , http = require('http')
	  , app = express()
	  , server = http.createServer(app);

	var bodyParser = require('body-parser');

	// fabicon
	/*
	var favicon = require('serve-favicon');
	app.use(favicon('./images/favicon.ico'));
	*/


	app.use(bodyParser.json() );       // to support JSON-encoded bodies
	app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
	  extended: true
	})); 

	var multer = require('multer'); 
	app.use(multer()); // for parsing multipart/form-data

	app.use(require('express-domain-middleware')); // for error handling

	//app.use(require('compression')());  // gzip compress  - nginx 에서 담당.

	// read config file
	global.config = require('./configs/config');
	// add setting values
	function adjustDbSettings(config)
	{

		if(! ('multipleStatements' in config))
			config['multipleStatements'] = true;	// for stored procedure output param

		if(! ('connectionLimit' in config))
			config['connectionLimit'] = 20;

		if(! ('waitForConnections' in config))
			config['waitForConnections'] = true;

		if(! ('autoReconnect' in config))
			config['autoReconnect'] = true;

		if(! ('useConnectionPooling' in config))
			config['useConnectionPooling'] = true;

		if(! ('reconnectDelay' in config))
			config['reconnectDelay'] = 500;

		if(! ('maxReconnectAttempts' in config))
			config['maxReconnectAttempts'] = 25;

		if(! ('keepAlive' in config))
			config['keepAlive'] = true;

		if(! ('keepAliveInterval' in config))
			config['keepAliveInterval'] = 30000;

	}

	adjustDbSettings(global.config.database.master);
	adjustDbSettings(global.config.database.replica);
	adjustDbSettings(global.config.database.log);


	var MySQLConnectionManager = require('mysql-connection-manager'); // for mysql db HA , pool
	global.master_db = new MySQLConnectionManager(global.config.database.master);
	global.replica_db = new MySQLConnectionManager(global.config.database.replica);
	global.log_db = new MySQLConnectionManager(global.config.database.log);


	/************************************************** route ******************************************/

	var verArray = ['v0.7' ,'v1.0'];

	//AUTH 
	var prefix = '/auth/';
	var commonApiArray = ['loginWithEmail'
					,'loginWithFacebook'
					,'logout'
					,'checkSessionId'
					,'resetPwd'
					,'updatePwd'
					,'addDevice'
					,'prepareProfilePics'
					,'registerProfilePics'
					,'deleteProfilePics'
					,'prepareBackgroundPic'
					,'registerBackgroundPic'
					,'deleteBackgroundPic'
					,'updateSetting'
					,'updateProfile'
					,'getSetting'
					,'appBackground'
					,'appForeground'];

	for(var v=0 ; v < verArray.length ; v++)
	{
		for(var a=0 ; a < commonApiArray.length ; a++)
		{
			var api = require('./routes/' + verArray[v] + prefix + commonApiArray[a]);
			app.use('/' + verArray[v] + prefix + commonApiArray[a] , api);
		}
	}

	var checkRegisteredEmail = require('./routes/v1.0/auth/checkRegisteredEmail');
	app.use('/v1.0/auth/checkRegisteredEmail' , checkRegisteredEmail);

	var utf8test = require('./routes/v1.0/auth/utf8test');
	app.use('/v1.0/auth/utf8test' , utf8test);


	// ARTICLE 
	prefix = '/article/';
	commonApiArray = ['getExplorer'
					,'getMetroExplorer'
					,'getArticleList'
					,'getArticle'
					,'getArticleWithEncryptedId'
					,'like'
					,'unlike'
					,'getArticleLikeUserList'
					,'getCommentList'
					,'registerComment'
					,'deleteComment'
					,'report'
					,'updateArticle'
					,'prepareArticle'
					,'registerArticle'
					,'getUploadInfo'
					,'deleteArticle'
					,'incViewCount'
					,'incShareCount'
					,'objectDownload'
					,'editStart'
					,'editCancel'];

	for(var v=0 ; v < verArray.length ; v++)
	{
		for(var a=0 ; a < commonApiArray.length ; a++)
		{
			var api = require('./routes/' + verArray[v] + prefix + commonApiArray[a]);
			app.use('/' + verArray[v] + prefix + commonApiArray[a] , api);
		}
	}

	var changeState = require('./routes/v1.0/article/changeState');
	app.use('/v1.0/article/changeState' , changeState);

	var changeGifState = require('./routes/v1.0/article/changeGifState');
	app.use('/v1.0/article/changeGifState' , changeGifState);

	var deleteGif = require('./routes/v1.0/article/deleteGif');
	app.use('/v1.0/article/deleteGif' , deleteGif);

	var getTagExplorer = require('./routes/v1.0/article/getTagExplorer');
	app.use('/v1.0/article/getTagExplorer' , getTagExplorer);

	var getSimpleTagExplorer = require('./routes/v1.0/article/getSimpleTagExplorer');
	app.use('/v1.0/article/getSimpleTagExplorer' , getSimpleTagExplorer);

	var prepareGif = require('./routes/v1.0/article/prepareGif');
	app.use('/v1.0/article/prepareGif' , prepareGif);

	var registerGif = require('./routes/v1.0/article/registerGif');
	app.use('/v1.0/article/registerGif' , registerGif);

	var getReservedHashTagList = require('./routes/v1.0/article/getReservedHashTagList');
	app.use('/v1.0/article/getReservedHashTagList' , getReservedHashTagList);

	var getArticleState = require('./routes/v1.0/article/getArticleState');
	app.use('/v1.0/article/getArticleState' , getArticleState);

	var getObjectSlotInfoFilePath = require('./routes/v1.0/article/getObjectSlotInfoFilePath');
	app.use('/v1.0/article/getObjectSlotInfoFilePath' , getObjectSlotInfoFilePath);


	// MSG 
	prefix = '/msg/';
	commonApiArray=['getMsgList'
					,'getMsgList2'
					,'confirmMsgList'
					,'confirmAllMsg'];


	for(var v=0 ; v < verArray.length ; v++)
	{
		for(var a=0 ; a < commonApiArray.length ; a++)
		{
			var api = require('./routes/' + verArray[v] + prefix + commonApiArray[a]);
			app.use('/' + verArray[v] + prefix + commonApiArray[a] , api);
		}
	}

	// USER 
	prefix = '/user/';
	commonApiArray=['searchUser'
					,'follow'
					,'unfollow'
					,'block'
					,'unblock'
					,'getUserInfo'
					,'getProfileViewCount'
					,'getFriendList'
					,'getGroupUserList'
					,'getBadgeInfo'
					,'getUserListWithFacebookIdList'
					,'notifyFacebookFriend'];

	for(var v=0 ; v < verArray.length ; v++)
	{
		for(var a=0 ; a < commonApiArray.length ; a++)
		{
			var api = require('./routes/' + verArray[v] + prefix + commonApiArray[a]);
			app.use('/' + verArray[v] + prefix + commonApiArray[a] , api);
		}
	}

	var api = require('./routes/v1.0/user/getFeaturedUserList');
	app.use('/v1.0/user/getFeaturedUserList' , api);



	// path exception 
	app.use(function(req, res) {

		var err = new Error(req.path);
		err.code = '509'; // API is not supported.
		throw err;
	});

	// error handler
	app.use(require('./routes/handlers/error_handler'));

	// event handler max: 30
	process.setMaxListeners(30);

	// listener 
	server.listen(global.config.listen_port, function() 
	{
		  console.log('Express server listening on port ' + server.address().port + ', PID : ' + process.pid);
	});

} //worker
